<template>
  <div class="search-container">
    <div class="search-bar" :class="{ 'focused': isFocused }">
      <el-input
        v-model="keyword"
        placeholder="搜索问题或用户"
        class="search-input"
        :prefix-icon="Search"
        clearable
        @focus="handleFocus"
        @blur="handleBlur"
        @keyup.enter="handleSearch"
        @input="fetchSearchSuggestions"
        @keydown.down.prevent="moveSelection(1)"
        @keydown.up.prevent="moveSelection(-1)"
      >
        <template #append>
          <el-button type="primary" @click.stop="handleSearch">搜索</el-button>
        </template>
      </el-input>
      
      <!-- 搜索下拉面板 -->
      <div v-if="showDropdown" class="search-dropdown">
        <!-- 搜索中提示 -->
        <div v-if="isLoading" class="loading-section">
          <div class="loading-spinner">
            <el-icon class="is-loading"><Loading /></el-icon>
          </div>
          <span>正在搜索...</span>
        </div>
        
        <!-- 错误提示 -->
        <div v-else-if="searchError" class="error-section">
          <el-icon><Warning /></el-icon>
          <span>{{ searchError }}</span>
          <el-button type="text" size="small" @click="fetchSearchSuggestions">重试</el-button>
        </div>
        
        <!-- 搜索建议 -->
        <div v-else-if="suggestions.length > 0" class="suggestions-section">
          <div class="section-header">
            <span>搜索建议</span>
          </div>
          <div class="suggestions-list">
            <div 
              v-for="(item, index) in suggestions" 
              :key="'suggestion-' + index" 
              class="suggestion-item"
              :class="{ 'active': selectedIndex === index }"
              @click="selectKeyword(item)"
              @mouseover="selectedIndex = index"
            >
              <el-icon><Search /></el-icon>
              <span v-html="highlightMatch(item)"></span>
            </div>
          </div>
        </div>
        
        <!-- 历史搜索 -->
        <div v-if="history.length > 0" class="history-section">
          <div class="section-header">
            <span>搜索历史</span>
            <el-button type="text" size="small" @click="clearHistory">清除</el-button>
          </div>
          <div class="history-list">
            <div 
              v-for="(item, index) in history" 
              :key="'history-' + index" 
              class="history-item"
              :class="{ 'active': selectedIndex === suggestions.length + index }"
              @click="selectKeyword(item)"
              @mouseover="selectedIndex = suggestions.length + index"
            >
              <el-icon><Clock /></el-icon>
              <span>{{ item }}</span>
              <el-icon class="delete-icon" @click.stop="removeHistoryItem(index)"><Delete /></el-icon>
            </div>
          </div>
        </div>
        
        <!-- 热门搜索 -->
        <div v-if="hotKeywords.length > 0" class="hot-section">
          <div class="section-header">
            <span>热门搜索</span>
          </div>
          <div class="hot-list">
            <el-tag
              v-for="(item, index) in hotKeywords"
              :key="'hot-' + index"
              class="hot-item"
              @click="selectKeyword(item)"
            >
              {{ item }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Search, Clock, Delete, Loading, Warning } from '@element-plus/icons-vue';
import { 
  getHotKeywords, 
  getSearchHistory, 
  clearSearchHistory, 
  getSearchSuggestions
} from '../api/search';
import { debounce } from 'lodash-es';

const props = defineProps({
  initialKeyword: {
    type: String,
    default: ''
  }
});

const router = useRouter();
const keyword = ref(props.initialKeyword || '');
const isFocused = ref(false);
const showDropdown = ref(false);
const history = ref([]);
const hotKeywords = ref([]);
const suggestions = ref([]);
const selectedIndex = ref(null);
const isLoading = ref(false);
const searchError = ref(null);

// 监听页面点击，关闭下拉面板
const handleClickOutside = (event) => {
  const container = document.querySelector('.search-container');
  if (container && !container.contains(event.target)) {
    showDropdown.value = false;
  }
};

// 组件挂载时添加点击事件监听
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  loadHotKeywords();
  loadSearchHistory();
});

// 组件卸载前移除点击事件监听
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 监听 initialKeyword 属性变化
watch(() => props.initialKeyword, (newValue) => {
  keyword.value = newValue || '';
});

// 处理搜索框获得焦点
const handleFocus = () => {
  isFocused.value = true;
  showDropdown.value = true;
  
  // 如果已有关键词，获取搜索建议
  if (keyword.value.trim()) {
    fetchSearchSuggestions();
  }
};

// 处理搜索框失去焦点
const handleBlur = () => {
  isFocused.value = false;
  // 不要马上关闭下拉面板，因为可能是用户点击面板中的选项
  // 由handleClickOutside处理关闭
};

// 获取搜索建议 - 使用debounce防止频繁请求
const fetchSearchSuggestions = debounce(async () => {
  if (!keyword.value.trim()) {
    suggestions.value = [];
    return;
  }
  
  try {
    isLoading.value = true;
    searchError.value = null;
    const res = await getSearchSuggestions(keyword.value.trim(), 5);
    if (res.code === 200 && Array.isArray(res.data)) {
      suggestions.value = res.data;
    }
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    suggestions.value = [];
    searchError.value = '获取搜索建议失败，请稍后再试';
  } finally {
    isLoading.value = false;
  }
}, 300);

// 加载热门搜索关键词
const loadHotKeywords = async () => {
  try {
    const res = await getHotKeywords(10);
    if (res.code === 200 && Array.isArray(res.data)) {
      hotKeywords.value = res.data;
    } else {
      // 备用数据
      hotKeywords.value = [
        '前端开发',
        'Vue.js',
        'Java',
        'Python',
        'Spring Boot',
        '算法',
        '面试题',
        '微服务'
      ];
    }
  } catch (error) {
    console.error('获取热门搜索关键词失败:', error);
    // 加载失败时使用备用数据
    hotKeywords.value = [
      '前端开发',
      'Vue.js',
      'Java',
      'Python',
      'Spring Boot'
    ];
  }
};

// 加载搜索历史
const loadSearchHistory = async () => {
  try {
    // 尝试从API加载
    const res = await getSearchHistory(10);
    if (res.code === 200 && Array.isArray(res.data)) {
      history.value = res.data;
    } else {
      // 如果API加载失败，从localStorage获取搜索历史
      const historyData = localStorage.getItem('searchHistory');
      if (historyData) {
        history.value = JSON.parse(historyData) || [];
      } else {
        history.value = [];
      }
    }
  } catch (error) {
    console.error('获取搜索历史失败:', error);
    // 如果API加载失败，从localStorage获取搜索历史
    const historyData = localStorage.getItem('searchHistory');
    if (historyData) {
      history.value = JSON.parse(historyData) || [];
    } else {
      history.value = [];
    }
  }
};

// 清除搜索历史
const clearHistory = async () => {
  try {
    // 清除本地搜索历史
    localStorage.removeItem('searchHistory');
    history.value = [];
    
    // 调用API清除远程历史
    await clearSearchHistory();
    ElMessage.success('搜索历史已清除');
  } catch (error) {
    console.error('清除搜索历史失败:', error);
    ElMessage.error('清除搜索历史失败');
  }
};

// 保存搜索历史到本地存储
const saveSearchHistoryToLocal = (keyword) => {
  try {
    // 获取现有历史
    let historyData = [];
    const existingHistory = localStorage.getItem('searchHistory');
    if (existingHistory) {
      historyData = JSON.parse(existingHistory);
    }
    
    // 去重：如果已存在相同关键词，先移除
    historyData = historyData.filter(item => item !== keyword);
    
    // 添加到开头
    historyData.unshift(keyword);
    
    // 限制历史记录数量为10条
    if (historyData.length > 10) {
      historyData = historyData.slice(0, 10);
    }
    
    // 保存回localStorage
    localStorage.setItem('searchHistory', JSON.stringify(historyData));
    
    // 更新当前显示的历史
    history.value = historyData;
  } catch (error) {
    console.error('保存搜索历史失败:', error);
  }
};

// 选择关键词
const selectKeyword = (word) => {
  keyword.value = word;
  nextTick(() => {
    handleSearch();
  });
};

// 处理搜索
const handleSearch = () => {
  if (!keyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }
  
  const searchKeyword = keyword.value.trim();
  console.log('开始搜索:', searchKeyword);
  
  // 保存搜索历史到本地
  saveSearchHistoryToLocal(searchKeyword);
  
  // 判断是在搜索页还是其他页面
  if (router.currentRoute.value.path === '/search') {
    // 已在搜索页，触发自定义事件通知SearchPage更新
    window.dispatchEvent(new CustomEvent('search-keyword-changed', {
      detail: {
        keyword: searchKeyword
      }
    }));
  } else {
    // 不在搜索页，跳转到搜索页
    router.push({
      path: '/search',
      query: { keyword: searchKeyword }
    });
  }
};

// 移除历史记录项
const removeHistoryItem = (index) => {
  const removedItem = history.value.splice(index, 1)[0];
  saveSearchHistoryToLocal(removedItem);
};

// 高亮匹配关键词
const highlightMatch = (text) => {
  if (!keyword.value.trim()) return text;
  
  try {
    // 转义正则特殊字符
    const escapeRegExp = (string) => {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    };
    
    const keywordEscaped = escapeRegExp(keyword.value.trim());
    const regex = new RegExp(`(${keywordEscaped})`, 'gi');
    return text.replace(regex, '<span class="highlight">$1</span>');
  } catch (error) {
    console.error('高亮处理失败:', error);
    return text;
  }
};

// 移动选择
const moveSelection = (direction) => {
  if (!showDropdown.value) {
    showDropdown.value = true;
    return;
  }
  
  const totalItems = suggestions.value.length + history.value.length + hotKeywords.value.length;
  if (totalItems === 0) return;
  
  if (selectedIndex.value === null) {
    selectedIndex.value = direction > 0 ? 0 : totalItems - 1;
  } else {
    selectedIndex.value = (selectedIndex.value + direction + totalItems) % totalItems;
  }
  
  // 如果选择了某项，直接更新输入框
  if (selectedIndex.value < suggestions.value.length) {
    // 选择了搜索建议
    keyword.value = suggestions.value[selectedIndex.value];
  } else if (selectedIndex.value < suggestions.value.length + history.value.length) {
    // 选择了历史记录
    const historyIndex = selectedIndex.value - suggestions.value.length;
    keyword.value = history.value[historyIndex];
  } else {
    // 选择了热门搜索
    const hotIndex = selectedIndex.value - suggestions.value.length - history.value.length;
    keyword.value = hotKeywords.value[hotIndex];
  }
};
</script>

<style scoped>
.search-container {
  position: relative;
  width: 100%;
}

.search-bar {
  width: 100%;
  transition: all 0.3s;
}

.search-bar.focused {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-input {
  width: 100%;
}

.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-top: 5px;
  z-index: 10;
  max-height: 400px;
  overflow-y: auto;
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #909399;
}

.history-list, .suggestions-list {
  padding: 8px 0;
}

.history-item, .suggestion-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover, .suggestion-item:hover, 
.history-item.active, .suggestion-item.active {
  background-color: #f0f7ff;
}

.history-item .el-icon, .suggestion-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.hot-section {
  padding-bottom: 8px;
}

.hot-list {
  display: flex;
  flex-wrap: wrap;
  padding: 8px 12px;
  gap: 8px;
}

.hot-item {
  cursor: pointer;
  transition: all 0.2s ease;
}

.hot-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 新增搜索建议样式 */
.suggestions-section {
  border-bottom: 1px solid #f0f0f0;
}

.suggestion-item {
  color: #409EFF;
}

.highlight {
  background-color: #e6f7ff;
  font-weight: 500;
  border-radius: 2px;
  padding: 0 2px;
}

.delete-icon {
  margin-left: auto;
  cursor: pointer;
  color: #909399;
  opacity: 0;
  transition: opacity 0.2s;
}

.history-item:hover .delete-icon {
  opacity: 1;
}

.delete-icon:hover {
  color: #f56c6c;
}

.loading-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.loading-spinner {
  margin-right: 8px;
}

.error-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.error-section .el-icon {
  margin-right: 8px;
}
</style> 